import time
from rest_framework.viewsets import ModelViewSet
from apps.meiduo_admin.serializers.image import ImageSerializer,SKUSerializer
from apps.goods.models import SKUImage,SKU
from apps.meiduo_admin.utils import PageNum
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


#商品管理->图片管理->保存图片数据->新增图片  展示图片列表
class ImageView(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = ImageSerializer
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):

        sku_id = request.data.get('sku')
        image = request.FILES.get('image')     #请求体体中的文件request.FILES

        from fdfs_client.client import Fdfs_client             #1.导入客户端
        client = Fdfs_client('utils/fastdfs/client.conf')      #2.创建客户端
        result = client.upload_by_buffer(image.read())         #3.fastdfs上传二进制文件

        if result.get('Status') != 'Upload successed.':
            from rest_framework import status
            return Response(status=status.HTTP_403_FORBIDDEN)
        img_url = result['Remote file_id']
        img = SKUImage.objects.create(sku_id=sku_id,image = img_url)

        return Response({
            "id":img.id,
            'sku':sku_id,
            'image':img_url,

           },status=201)      #增/改响应状态码201



    # def update(self, request,pk):
    #     #更新图片重写视图方法pk:表中的id，  sku_id：外键商品id  （1.上传fdfs,2.修改数据库）
    #     sku_id = request.data.get('sku')
    #     image = request.FILES.get('image')
    #
    #     from fdfs_client.client import Fdfs_client
    #     client = Fdfs_client('utils/fastdfs/client.conf')
    #     result = client.upload_by_buffer(image.read())
    #
    #     if result.get('Status') != 'Upload successed.':
    #         from rest_framework import status
    #         return Response(status=status.HTTP_403_FORBIDDEN)
    #     img_url = result['Remote file_id']
    #
    #     img = SKUImage.objects.get(id=pk)
    #     img_url1 = str(img.image)
    #     client.delete_file(img_url1)   #image地址为url类型，需转为字符串类型，才可以被删除
    #
    #     img.image = img_url
    #     print(img.image)
    #     img.save()
    #
    #     return Response({
    #         'id':img.id,
    #         'sku':sku_id,
    #         'image':img_url1
    #         },status=201)

#商品管理->图片管理->保存图片数据->获取SKU商品id
from rest_framework.generics import ListAPIView
class SKUView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer
